package cn.dnui_wnx725.dnuifood_16110100725.model;

import java.util.List;

import cn.dnui_wnx725.dnuifood_16110100725.Server;
import cn.dnui_wnx725.dnuifood_16110100725.listener.ListListener;
import cn.dnui_wnx725.dnuifood_16110100725.listener.TListener;
import cn.dnui_wnx725.dnuifood_16110100725.service.Service;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//获取数据model基类
public class RetrofitBaseModel {
    Service service;
    Retrofit retrofit;
//获取retrofit对象
    public Retrofit getRetrofit(){
        retrofit = new Retrofit.Builder().baseUrl(Server.BASEURL)
                .addConverterFactory(GsonConverterFactory.create()).build();
        return retrofit;
    }
//获取service的实现类，由retrofit内部实现
    public Service getService(){
        service=retrofit.create(Service.class);
        return  service;
    }
    //执行获取数据的方法，获取一条数据
    public <T>void callenqueue(Call<T> call, final TListener<T> tListener){
        call.enqueue(new Callback<T>() {
            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if(response.body()!=null && response.isSuccessful()){
                    //获取成功，调用onResponse方法，将输入传去tListener
                    tListener.onResponse(response.body());

                }
                else{
                    //获取数据为空，把错误信息传入
                    tListener.onFail("onResponse fail");//使用了java的回调机制
                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                //获取数据失败，把错误信息传入
                tListener.onFail(t.toString());
            }
        });
    }
    //执行获取数据的方法，获取多条数据
    public <T>void callenqueueList(Call<List<T>> call, final ListListener<T> listListener){
        call.enqueue(new Callback<List<T>>() {
            @Override
            public void onResponse(Call<List<T>> call, Response<List<T>> response) {
                if(response.body()!=null && response.isSuccessful()){

                    listListener.onResponse(response.body());

                }
                else{

                    listListener.onFail("onResponse fail");//使用了java的回调机制
                }
            }

            @Override
            public void onFailure(Call<List<T>> call, Throwable t) {
                listListener.onFail("onResponse fail");//使用了java的回调机制
            }
        });
    }
}
